<template>
  <div>
    <el-input type="file" @change.native="importf($event)"></el-input>
    <el-button @click="xlsxFormatter(postdata,datalist)">项目基本信息</el-button>
    <el-button @click="xlsxFormatter(updatezileixing,allprojectlist)">治理类型</el-button>
    <el-button @click="xlsxFormatter(updatesgjd,allprojectlist)">施工阶段</el-button>
    <el-button @click="xlsxFormatter(updatesgstate,allprojectlist)">施工状态</el-button>
    <el-button @click="xlsxFormatter(updateshusuo,allprojectlist)">所属项目部/地市</el-button>
    <el-button @click="userone">用户1</el-button>
    <el-button @click="userfore">用户2</el-button>
    <el-button @click="updatediyu">地域</el-button>
      <el-button @click="downlog">下载</el-button>
  </div>
</template>
<script>
import XLSX from "xlsx";
import axios from "axios";
import { allprojectlist } from "./allprojectlist";
export default {
  data() {
    return {
      alllist: [],
      updateStatus: [],
      datalist: [],
      starting:false,
      datalistCopy: [],
      zllx: [
        "更换",
        "新增",
        "改造",
        "新增改造",
        "频繁停电",
        "卡脖子",
        "重过载",
        "低电压"
      ],
      sgjd: [
        "郑州",
        "开封",
        "商丘",
        "周口",
        "驻马店",
        "信阳",
        "南阳",
        "洛阳",
        "平顶山"
      ],
      allprojectlist,
      loglist:""
    };
  },
  methods: {
    handelemove($event){
      window.target = $event.target
      console.log()
    },
    updatediyu(){
        const list = this.datalist.map(item=>{
          return `${item.sname}-${item.xname}`
        });
        const sxlist = Array.from(new Set(list)).map(item=>{
          const name = item.split("-")
          return {sname:name[0],xname:name[1]}
        })
        let text = `市名称            县名称\r\n`
        sxlist.forEach(item=>{
          text+=`${item.sname}            ${item.xname}\r\n`
        })
        this.download(text)
    },
    download(text){
      const file = new Blob([text]);
      const a = document.createElement("a");
      const url = URL.createObjectURL(file);
      a.href = url;
      a.download = `log.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    },
    datafomatter(){
      const _this = this;
      let list = [];
      let list1 = [];
      this.datalist.forEach(ele=>{
        if(list1.includes(ele.xmmc)){
          return;
        }else {
          const list3 = _this.datalist.filter(item=>{
            return item.xmmc ==ele.xmmc
          });

          const list4 = list3.map(element=>{
            return {name:element.location,
                  value:[element.y,element.x]
                  }
          });
          list.push({
            ...ele,
            xaddress:JSON.stringify(list4)
          });
          list1.push(ele.xmmc)
        }
      });
      this.datalist = list
    },
    importf(obj) {
      let _this = this;
      var wb; //读取完成的数据
      var rABS = false; //是否将文件读取为二进制字符串
      var datajson = new Array();
      var updata;
      obj = obj.target;
      if (!obj.files) {
        return;
      }
      var f = obj.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        var data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            //手动转化
            type: "base64"
          });
        } else {
          wb = XLSX.read(data, {
            type: "binary"
          });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        console.log(wb.Sheets.length)
        datajson = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        // _this.xlsxFormatter(datajson);
        _this.datalistCopy = JSON.parse(JSON.stringify(datajson));
        _this.datalist = datajson;
        console.log(datajson);
        // _this.ygformatter(datajson)
        // _this.datafomatter()
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
      //
    },
    ygformatter(datalist){
      let xmmc = datalist.shift();                                      
      xmmc =Object.values(xmmc)[0].split(":")[1]
      let keylist=datalist.shift();
      if(!this.xmmclist.includes(xmmc)){
        this.datalist.push(datalist.map(item=>{
          return {wlmc:item.__EMPTY,
                  ggxh:item.__EMPTY_1,
                  dw:item.__EMPTY_2,
                  sl:item.__EMPTY_3,
                  dj:item.__EMPTY_4,
                  hj:item.__EMPTY_5,
                  jhr:item.__EMPTY_6,
                  jhdd:item.__EMPTY_7,
                  jhylsj:item.__EMPTY_8,
                  remark:item.__EMPTY_9     
          }
        }))
      }
      console.log(xmmc);
      console.log(datalist)
    },
    xlsxFormatter(fn, data) {
      let _this = this;
      if(_this.starting){
        return false;
      }
      if (data.length === 0) {
        this.$message({
          message: "未获得数据，无法上传",
          type: "warning"
        });
        return false;
      }
      _this.starting = true
      _this.splitpost(fn, data, 500, 5);
    },
    getid(name) {
      let a = this.datalist.filter(item => {
        return item.name.includes(name.replace("分部",""))
      });
      return a[0];
    },
    postdata(list) {

      let _this = this;
        this.$axios({
          method: "post",
          url: "http://192.168.31.16:8080/pwregion/updateRegionList",
          data:{list}
        })
          .then(response => {
            _this.loglist =_this.loglist+ `${new Date()} success:${JSON.stringify(list)}:\r\n       ${JSON.stringify(response.data)}\r\n`
            _this.updateStatus.push({
              name: list,
              status: "success",
              success: response.data
            });
          })
          .catch(error => {
            _this.loglist =_this.loglist+ `${new Date()} error:${JSON.stringify(list)}:\r\n       ${JSON.stringify(error.status)}\r\n`
            _this.updateStatus.push({
              name: list,
              status: "error",
              error: error
            });
          });
    },
    downlog(){
      const file = new Blob([this.loglist]);
      const a = document.createElement("a");
      const url = URL.createObjectURL(file);
      a.href = url;
      a.download = `log.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    },
    splitpost(fn, data, k, time) {
      let _this = this;
      
      if (data.length == 0) {
        console.log("全部发送完成");
        _this.starting = false
        return false;
      } else {
        fn(data.splice(0, k));
        console.log("发送完成");
        setTimeout(function() {
          return _this.splitpost(fn, data, k, time);
        }, time);
      }
    },
    getalllist() {
      let _this = this;
      this.$axios({
        method: "post",
        url: "http://192.168.31.153:8081/pwregion/findAll"
      })
        .then(response => {
          _this.alllist = response.data.data;
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    addarea(data) {
      let _this = this;
      this.$axios({
        method: "post",
        url: "http://192.168.31.153:8081/pwregion/addRegion",
        data: data
      })
        .then(response => {
          _this.alllist = response.data;
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    updatezileixing(list) {
      let _this = this;
      list.forEach(item => {
        let zllx;
        _this.zllx.forEach(element => {
          if (item.xmmc && item.xmmc.includes(element)) {
            zllx = element;
          }
          if (!zllx && item.fbmc && item.fbmc.includes(element)) {
            zllx = element;
          }
        });
        let fromdata = new FormData();
        fromdata.append("jcxxid", item.jcxxid);
        fromdata.append("zllx", zllx);
        this.$axios({
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          url: "http://192.168.31.16:8081/pwjcxx/updateJCXX",
          data: fromdata
        })
          .then(response => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "success",
              success: response.data
            });
          })
          .catch(error => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "error",
              error: error
            });
          });
      });
    },
    updatesgjd(list) {
      let _this = this;
      list.forEach(item => {
        let sgjd;
        _this.sgjd.forEach(element => {
          if (item.xmmc && item.xmmc.includes(element)) {
            sgjd = "第二阶段";
          }
        });
        let fromdata = new FormData();
        fromdata.append("jcxxid", item.jcxxid);
        fromdata.append("sgjd", sgjd);
        this.$axios({
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          url: "http://192.168.31.16:8081/pwjcxx/updateJCXX",
          data: fromdata
        })
          .then(response => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "success",
              success: response.data
            });
          })
          .catch(error => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "error",
              error: error
            });
          });
      });
    },

    updatesgstate(list) {
      let _this = this;
      list.forEach(item => {
        let xmstate = parseInt(Math.random() * 3 + 1);
        let xcsgzt = parseInt(Math.random() * 2 + 1);
        let fromdata = new FormData();
        fromdata.append("jcxxid", item.jcxxid);
        fromdata.append("xmstate", xmstate);
        fromdata.append("xcsgzt", xcsgzt);
        this.$axios({
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          url: "http://192.168.31.16:8081/pwjcxx/updateJCXX",
          data: fromdata
        })
          .then(response => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "success",
              success: response.data
            });
          })
          .catch(error => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "error",
              error: error
            });
          });
      });
    },
    updateshusuo(list) {
      let _this = this;
      list.forEach(item => {
          if(!item.deptname){
              return;
          }
          let regionid = _this.getid(item.deptname)
        let fromdata = new FormData();
        fromdata.append("jcxxid", item.jcxxid);
   
  if(!regionid) {
     return 
  }   
fromdata.append("ssdeptid",regionid.id);

        this.$axios({
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          url: "http://192.168.31.16:8081/pwjcxx/updateJCXX",
          data: fromdata
        })
          .then(response => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "success",
              success: response.data
            });
          })
          .catch(error => {
            _this.updateStatus.push({
              name: item.NAME,
              status: "error",
              error: error
            });
          });
      });
    },
    locked(){
        let fromdata = new FormData();
        fromdata.append("filecategoryid", 5);
        fromdata.append("commonid", 5);
        this.$axios({
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          url: "http://192.168.31.16:8080/pwnewfilelock/add",
          data: fromdata
        })
    },
    userone(){
        const _this=this;
        setInterval(function(){
_this.login({username:"A001",password:"123456"})
        },1)
    },
    userfore(){
      const _this = this ;
      setInterval(function(){
      _this.login({username:"B005",password:"123456"})
      },1)
    },
    login(userinfo){
      const _this = this;
      this.$axios({
      method: "get",
      url:
        `http://192.168.31.16:8080/loginSubmit?loginName=${userinfo.username}&password=${userinfo.password}`
    })
      .then(response => {
        _this.locked()
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
    },

  },
  mounted() {
    this.$axios({
      method: "get",
      url:
        "http://192.168.31.16:8080/loginSubmit?loginName=A001&password=123456"
    })
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
    // this.getalllist();
    window.updateStatus = this.updateStatus;
  }
};
</script>
